package com.lbl.demo02_consumer_user_81.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by 李柏霖
 * 2020/11/23 11:19
 */

@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
    @Autowired
    RestTemplate rt;//当前是使用RestTemplate调用demo01的数据
    @Autowired
    DiscoveryClient discoveryClient;

    //需要在启动类创建当前对象
    //然后由Autowired去获取
    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    public Object get(@PathVariable long id) {

        //获取 provider ip与端口
        List<ServiceInstance> list = discoveryClient.getInstances("demo01_provider_user_8001");//服务id
        //表示运行中的服务对象
        ServiceInstance serviceInstance = list.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        log.info("host " + host);
        log.info("port " + port);
        //消费工程，只是调用其他服务来获得想要的数据
        String url = "http://" + host + ":" + port + "/users/11";//参1 地址
        //String url = "http://localhost:8001/users/11";//参1 地址
        String json = rt.getForObject(url, String.class);//参2：数据要转换成什么类型
        return json;
    }
}
